package com.minimalist.lindi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.config.mybatis.bo.PageResp;
import com.minimalist.common.entity.basic.enums.FileEnum;
import com.minimalist.common.entity.basic.vo.file.FileVO;
import com.minimalist.common.entity.lindi.enums.LindiEnterpriseAccountEnum;
import com.minimalist.common.entity.lindi.po.LindiEnterpriseAccount;
import com.minimalist.common.entity.lindi.vo.enterpriseaccount.LindiEnterpriseAccountQueryVO;
import com.minimalist.common.entity.lindi.vo.enterpriseaccount.LindiEnterpriseAccountVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.utils.GenerateUtil;
import com.minimalist.common.utils.Sm4Util;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.manager.LindiEnterpriseManager;
import com.minimalist.lindi.mapper.LindiEnterpriseAccountMapper;
import com.minimalist.lindi.service.LindiEnterpriseAccountService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 林地指标交易平台_企业用户表 服务层实现。
 *
 * @author 11987
 * @since 2025-03-31
 */
@Service
public class LindiEnterpriseAccountServiceImpl
        extends ServiceImpl<LindiEnterpriseAccountMapper
        , LindiEnterpriseAccount> implements LindiEnterpriseAccountService{

    @Autowired
    private LindiEnterpriseAccountMapper mapper;

    @Autowired
    private LindiEnterpriseManager enterpriseManager;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Override
    public void addEnterpriseAccount(LindiEnterpriseAccountVO enterpriseAccountVO){
        Assert.isFalse(enterpriseManager.checkEnterpriseNameRegistered(
                        enterpriseAccountVO.getEnterpriseName(), null)
                , () -> new BusinessException(LindiEnterpriseAccountEnum
                        .ErrorMsgEnum.ENTERPRISE_NAME_REGISTERED.getDesc()));
        Assert.isFalse(enterpriseManager.checkEnterpriseMobileRegistered(
                        enterpriseAccountVO.getEnterpriseMobile(), null)
                , () -> new BusinessException(LindiEnterpriseAccountEnum
                        .ErrorMsgEnum.ENTERPRISE_MOBILE_REGISTERED.getDesc()));
        LindiEnterpriseAccount enterpriseAccount = new LindiEnterpriseAccount();
        enterpriseAccount.setEnterpriseAccountId(UnqIdUtil.uniqueId());
        enterpriseAccount.setStatus(LindiEnterpriseAccountEnum.StatusEnum
                .NORMAL.getCode());
        enterpriseAccount.setEnterprisePassword(Sm4Util.encrypt(
                GenerateUtil.generateRandomPassword(12)));
        BeanUtil.copyProperties(enterpriseAccountVO, enterpriseAccount);
        mapper.insert(enterpriseAccount);
    }

    @Override
    public void deleteEnterpriseAccountByEnterpriseAccountId(Long enterpriseAccountId){
        LindiEnterpriseAccount enterpriseAccount =
                mapper.selectEnterpriseAccountByEnterpriseAccountId
                        (enterpriseAccountId);
        Assert.notNull(enterpriseAccount
                , () -> new BusinessException(LindiEnterpriseAccountEnum
                        .ErrorMsgEnum.ENTERPRISE_ACCOUNT_NOT_EXIST.getDesc()));
        mapper.deleteEnterpriseAccountByEnterpriseAccountId(
                enterpriseAccountId);
    }

    @Override
    public void updateEnterpriseAccountByEnterpriseAccountId(
            LindiEnterpriseAccountVO enterpriseAccountVO){
        Assert.isFalse(enterpriseManager.checkEnterpriseNameRegistered(
                        enterpriseAccountVO.getEnterpriseName()
                        , enterpriseAccountVO.getEnterpriseAccountId())
                , () -> new BusinessException(LindiEnterpriseAccountEnum
                        .ErrorMsgEnum.ENTERPRISE_NAME_REGISTERED.getDesc()));
        LindiEnterpriseAccount lindiEnterpriseAccount
                = mapper.selectEnterpriseAccountByEnterpriseAccountId(
                enterpriseAccountVO.getEnterpriseAccountId());
        Assert.notNull(lindiEnterpriseAccount
                , () -> new BusinessException(LindiEnterpriseAccountEnum
                        .ErrorMsgEnum.ENTERPRISE_ACCOUNT_NOT_EXIST.getDesc()));
        String oldPassword = lindiEnterpriseAccount.getEnterprisePassword();
        BeanUtil.copyProperties(enterpriseAccountVO
                , lindiEnterpriseAccount);
        // 如果密码字段为空或空字符串，则不更新密码，保持原密码
        if (enterpriseAccountVO.getEnterprisePassword() == null || 
            enterpriseAccountVO.getEnterprisePassword().trim().isEmpty()){
            lindiEnterpriseAccount.setEnterprisePassword(oldPassword);
        } else{
            lindiEnterpriseAccount.setEnterprisePassword(Sm4Util.encrypt(
                    enterpriseAccountVO.getEnterprisePassword()));
        }
        mapper.updateEnterpriseAccountByEnterpriseAccountId(
                lindiEnterpriseAccount);
    }

    @Override
    public PageResp<LindiEnterpriseAccountVO> getPageEnterpriseAccountList(
            LindiEnterpriseAccountQueryVO queryVO){
        Page<LindiEnterpriseAccount> page = mapper
                .selectPageEnterpriseAccountList(queryVO);
        List<LindiEnterpriseAccountVO> list = BeanUtil.copyToList(
                page.getRecords(), LindiEnterpriseAccountVO.class);
        return new PageResp<>(list, page.getTotalRow());
    }

    @Override
    public LindiEnterpriseAccountVO getEnterpriseAccountByEnterpriseAccountId(
            Long enterpriseAccountId){
        // 获取企业注册基本信息
        LindiEnterpriseAccount account = mapper
                .selectEnterpriseAccountByEnterpriseAccountId(enterpriseAccountId);
        Assert.notNull(account, () -> new BusinessException(
                LindiEnterpriseAccountEnum.ErrorMsgEnum.ENTERPRISE_ACCOUNT_NOT_EXIST
                        .getDesc()));

        LindiEnterpriseAccountVO accountVO = BeanUtil.copyProperties(
                account, LindiEnterpriseAccountVO.class);
        // 收集所有需要查询的文件ID
        List<Long> fileIds = new java.util.ArrayList<>();
        if (accountVO.getEnterpriseBusinessLicense() != null){
            fileIds.add(accountVO.getEnterpriseBusinessLicense());
        }
        if (accountVO.getEnterpriseTax() != null){
            fileIds.add(accountVO.getEnterpriseTax());
        }
        if (accountVO.getEnterpriseCode() != null){
            fileIds.add(accountVO.getEnterpriseCode());
        }
        if (accountVO.getEnterpriseIdcard1() != null){
            fileIds.add(accountVO.getEnterpriseIdcard1());
        }
        if (accountVO.getEnterpriseIdcard2() != null){
            fileIds.add(accountVO.getEnterpriseIdcard2());
        }
        if (accountVO.getEnterpriseAttorney() != null){
            fileIds.add(accountVO.getEnterpriseAttorney());
        }

        // 如果有文件ID需要查询
        if (!fileIds.isEmpty()){
            // 批量查询文件信息
            List<FileVO> fileVOList = fileFeignClient.getFileListByFileIds(fileIds).getData();
            if (fileVOList == null || fileVOList.isEmpty()){
                throw new BusinessException(FileEnum.ErrorMsg.NONENTITY_FILE.getDesc());
            }
            java.util.Map<Long, String> fileUrlMap = fileVOList
                    .stream()
                    .collect(java.util.stream.Collectors.toMap(
                            FileVO::getFileId,
                            FileVO::getFileUrl));
            // 设置文件URL
            if (accountVO.getEnterpriseBusinessLicense() != null){
                accountVO.setEnterpriseBusinessLicenseUrl(
                        fileUrlMap.get(accountVO.getEnterpriseBusinessLicense()));
            }
            if (accountVO.getEnterpriseTax() != null){
                accountVO.setEnterpriseTaxUrl(
                        fileUrlMap.get(accountVO.getEnterpriseTax()));
            }
            if (accountVO.getEnterpriseCode() != null){
                accountVO.setEnterpriseCodeUrl(
                        fileUrlMap.get(accountVO.getEnterpriseCode()));
            }
            if (accountVO.getEnterpriseIdcard1() != null){
                accountVO.setEnterpriseIdcard1Url(
                        fileUrlMap.get(accountVO.getEnterpriseIdcard1()));
            }
            if (accountVO.getEnterpriseIdcard2() != null){
                accountVO.setEnterpriseIdcard2Url(
                        fileUrlMap.get(accountVO.getEnterpriseIdcard2()));
            }
            if (accountVO.getEnterpriseAttorney() != null){
                accountVO.setEnterpriseAttorneyUrl(
                        fileUrlMap.get(accountVO.getEnterpriseAttorney()));
            }
        }
        accountVO.setEnterprisePassword(null);
        return accountVO;
    }

    @Override
    public String getEnterpriseAccountPasswordByMobile(String enterpriseMobile){
        LindiEnterpriseAccount account = mapper
                .selectEnterpriseAccountByEnterpriseMobile(enterpriseMobile
                        , null);
        Assert.notNull(account, () -> new BusinessException(
                LindiEnterpriseAccountEnum.ErrorMsgEnum.ENTERPRISE_ACCOUNT_NOT_EXIST
                        .getDesc()));
        return Sm4Util.decrypt(account.getEnterprisePassword());
    }

    @Override
    public List<LindiEnterpriseAccountVO> getEnterpriseAccountList(){
        List<LindiEnterpriseAccount> enterpriseAccountList = mapper
                .selectEnterpriseAccountList();
        if (enterpriseAccountList == null || enterpriseAccountList.isEmpty()){
            return List.of();
        }
        return BeanUtil.copyToList(enterpriseAccountList, LindiEnterpriseAccountVO.class);
    }
    
    @Override
    public LindiEnterpriseAccountVO loginByMobile(String mobile, String password) {
        try {
            // 根据手机号查询企业用户
            LindiEnterpriseAccount account = mapper.selectEnterpriseAccountByMobile(mobile);
            if (account == null) {
                return null;
            }
            
            // 验证密码
            String decryptedPassword = Sm4Util.decrypt(account.getEnterprisePassword());
            if (!password.equals(decryptedPassword)) {
                return null;
            }
            
            // 转换为VO并返回
            LindiEnterpriseAccountVO accountVO = BeanUtil.copyProperties(
                account, LindiEnterpriseAccountVO.class);
            
            // 设置文件URL
            setFileUrls(accountVO);
            
            // 清除密码信息
            accountVO.setEnterprisePassword(null);
            
            return accountVO;
            
        } catch (Exception e) {
            throw new BusinessException("登录验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 设置企业账户VO中的文件URL
     * @param accountVO 企业账户VO
     */
    private void setFileUrls(LindiEnterpriseAccountVO accountVO) {
        // 收集所有需要查询的文件ID
        List<Long> fileIds = new java.util.ArrayList<>();
        if (accountVO.getEnterpriseBusinessLicense() != null){
            fileIds.add(accountVO.getEnterpriseBusinessLicense());
        }
        if (accountVO.getEnterpriseTax() != null){
            fileIds.add(accountVO.getEnterpriseTax());
        }
        if (accountVO.getEnterpriseCode() != null){
            fileIds.add(accountVO.getEnterpriseCode());
        }
        if (accountVO.getEnterpriseIdcard1() != null){
            fileIds.add(accountVO.getEnterpriseIdcard1());
        }
        if (accountVO.getEnterpriseIdcard2() != null){
            fileIds.add(accountVO.getEnterpriseIdcard2());
        }
        if (accountVO.getEnterpriseAttorney() != null){
            fileIds.add(accountVO.getEnterpriseAttorney());
        }

        // 如果有文件ID需要查询
        if (!fileIds.isEmpty()){
            // 批量查询文件信息
            List<FileVO> fileVOList = fileFeignClient.getFileListByFileIds(fileIds).getData();
            if (fileVOList == null || fileVOList.isEmpty()){
                throw new BusinessException(FileEnum.ErrorMsg.NONENTITY_FILE.getDesc());
            }
            java.util.Map<Long, String> fileUrlMap = fileVOList
                    .stream()
                    .collect(java.util.stream.Collectors.toMap(
                            FileVO::getFileId,
                            FileVO::getFileUrl));
            // 设置文件URL
            if (accountVO.getEnterpriseBusinessLicense() != null){
                accountVO.setEnterpriseBusinessLicenseUrl(
                        fileUrlMap.get(accountVO.getEnterpriseBusinessLicense()));
            }
            if (accountVO.getEnterpriseTax() != null){
                accountVO.setEnterpriseTaxUrl(
                        fileUrlMap.get(accountVO.getEnterpriseTax()));
            }
            if (accountVO.getEnterpriseCode() != null){
                accountVO.setEnterpriseCodeUrl(
                        fileUrlMap.get(accountVO.getEnterpriseCode()));
            }
            if (accountVO.getEnterpriseIdcard1() != null){
                accountVO.setEnterpriseIdcard1Url(
                        fileUrlMap.get(accountVO.getEnterpriseIdcard1()));
            }
            if (accountVO.getEnterpriseIdcard2() != null){
                accountVO.setEnterpriseIdcard2Url(
                        fileUrlMap.get(accountVO.getEnterpriseIdcard2()));
            }
            if (accountVO.getEnterpriseAttorney() != null){
                accountVO.setEnterpriseAttorneyUrl(
                        fileUrlMap.get(accountVO.getEnterpriseAttorney()));
            }
        }
    }
}
